package com.ccl.service.impl;

import com.ccl.dao.CommentMapper;
import com.ccl.dao.StatisticMapper;
import com.ccl.entity.Comment;
import com.ccl.entity.Statistic;
import com.ccl.service.CommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private StatisticMapper statisticMapper;
    //根据文章id分页查询评论数据:分页
    @Override
    public PageInfo<Comment> findCommentsByArticleId(Integer articleId,Integer commentPageNum,Integer count) {
        commentPageNum =commentPageNum==null?1:commentPageNum;
        PageHelper.startPage(commentPageNum,count);
        List<Comment> comments = commentMapper.findCommentsByArticleId(articleId);
        PageInfo<Comment> pageInfo = new PageInfo<>(comments);
        return pageInfo;
    }
    //发表评论
    @Override
    public void pushComment(Comment comment) {
        //添加评论
        commentMapper.pushComment(comment);
        //更新文章的评论量+1
        Integer articleId = comment.getArticleId();
        statisticMapper.updateCommentNum(articleId);

    }

    @Override
    public Integer getCommentsNum() {
        return commentMapper.getCommentsNum();
    }

    @Override
    public List<Comment> getRecentComments(Integer num) {
        return commentMapper.getRecentComments(num);
    }
    //根据文章id删除评论
    @Override
    public void deleteByArticleId(Integer articleId) {
        commentMapper.deleteByArticleId(articleId);
    }

    @Override
    public PageInfo<Comment> findWithPage(Integer pageNum, Integer count) {
        PageHelper.startPage(pageNum,count);
        List<Comment> comments = commentMapper.findAll();
        PageInfo<Comment> pageInfo = new PageInfo<>(comments);
        return pageInfo;
    }
    //后台评论管理根据删除评论
    @Override
    public void deleteById(Integer id) {
        //获取articleId 通过id获取comment对象，在获取articleId
        Comment comment = commentMapper.findById(id);
        Integer articleId = comment.getArticleId();
        //根据articleId获取statistic对象
        Statistic statistic = statisticMapper.findByArticleId(articleId);
        //减少t_statistic中评论数量
        statistic.setCommentsNum(statistic.getCommentsNum()-1);//评论量减一
        statisticMapper.updateStatistic(statistic);
        //删除评论
        commentMapper.deleteById(id);
    }
}
